<!-- 有字符串拼接格式报红。不影响使用 -->
{% extends "base.html" %}

{% block title %}告警列表 - 告警系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="fw-bold text-primary">告警列表</h1>
    <div>
        <button class="btn btn-outline-secondary me-2" onclick="location.reload()">
            <i class="bi bi-arrow-clockwise"></i> 刷新
        </button>
        <div class="btn-group">
            <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                每页 {{ page_size }} 条
            </button>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="?page=1&page_size=5{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">5条/页</a></li>
                <li><a class="dropdown-item" href="?page=1&page_size=10{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">10条/页</a></li>
                <li><a class="dropdown-item" href="?page=1&page_size=20{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">20条/页</a></li>
                <li><a class="dropdown-item" href="?page=1&page_size=50{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">50条/页</a></li>
            </ul>
        </div>
    </div>
</div>

<!-- 搜索和批量操作区域 -->
<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap">
    <!-- 时间范围筛选 -->
    <div class="d-flex align-items-center mb-2 mb-md-0">
        <form method="get" class="d-flex flex-wrap">
            <div class="input-group me-2 mb-2" style="width: 200px;">
                <span class="input-group-text"><i class="bi bi-calendar"></i></span>
                <input type="date" name="start_date" class="form-control" value="{{ start_date }}">
            </div>
            
            <div class="input-group me-2 mb-2" style="width: 200px;">
                <span class="input-group-text"><i class="bi bi-calendar"></i></span>
                <input type="date" name="end_date" class="form-control" value="{{ end_date }}">
            </div>
            
            <button class="btn btn-outline-primary me-2 mb-2" type="submit">
                <i class="bi bi-filter"></i> 时间筛选
            </button>
            
            {% if start_date or end_date %}
            <a href="?page=1&page_size={{ page_size }}&search={{ search_query }}" class="btn btn-outline-secondary mb-2">
                <i class="bi bi-x-lg"></i> 清除时间
            </a>
            {% endif %}
        </form>
    </div>
    
    <!-- 搜索框和删除按钮 -->
    <div class="d-flex align-items-center">
        <!-- 搜索框 -->
        <form method="get" class="d-flex me-3 mb-2">
            <div class="input-group" style="width: 300px;">
                <input type="text" name="search" class="form-control" placeholder="输入告警类型、设备IP等关键词" 
                       value="{{ search_query }}" aria-label="搜索告警">
                <button class="btn btn-primary" type="submit">
                    <i class="bi bi-search"></i> 搜索
                </button>
                {% if search_query %}
                <a href="?page=1&page_size={{ page_size }}&start_date={{ start_date }}&end_date={{ end_date }}" class="btn btn-outline-secondary">
                    <i class="bi bi-x-lg"></i> 清除
                </a>
                {% endif %}
            </div>
        </form>
        
        <!-- 批量删除按钮 -->
        <div>
            <button id="deleteSelectedBtn" class="btn btn-danger mb-2" disabled onclick="deleteSelectedAlerts()">
                <i class="bi bi-trash"></i> 删除选中项
            </button>
        </div>
    </div>
</div>

{% if alarms and alarms|length > 0 %}
    <div class="card shadow-sm">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="bg-primary text-white">
                    <tr>
                        <th width="40" class="text-center">
                            <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)">
                        </th>
                        <th class="ps-4">序号</th>
                        <th>设备IP</th>
                        <th>告警时间</th>
                        <th>位置</th>
                        <th>告警类型</th>
                        <th class="text-center">告警图片</th>
                        <th class="text-center">播放回放</th>
                    </tr>
                </thead>
<tbody>
    {% for alarm in alarms %}
    <tr>
        <td class="text-center">
            <input type="checkbox" class="alert-checkbox" value="{{ alarm.AlarmId }}" onchange="updateDeleteButtonState()">
        </td>
        <td class="ps-4 fw-medium">{{ (page - 1) * page_size + loop.index }}</td>
        <td class="fw-medium">{{ alarm.BoardIp }}</td>
        <td>{{ alarm.CreateTime.strftime('%Y-%m-%d %H:%M:%S') }}</td>
        <td>
            {% if alarm.passage %}
                {{ alarm.passage.MediaDesc }}
            {% else %}
                未知位置
            {% endif %}
        </td>
        <td>
            {{ alarm.ResultDescription or '无描述' }}
        </td>
        <td class="text-center">
            {% if alarm.ImagePath %}
                <img src="/api/alerts/image/{{ alarm.ImagePath | urlencode }}" 
                     alt="告警图片" 
                     class="alert-image img-thumbnail" 
                     style="width: 100px; height: auto; cursor: pointer;"
                     onclick="showImageModal('{{ alarm.ImagePath | urlencode }}')"
                     onerror="this.src='/static/images/default-alert.jpg'; this.title='图片加载失败'">
            {% else %}
                <span class="text-muted">无图片</span>
            {% endif %}
        </td>
        <td class="text-center">
            <button class="btn btn-sm btn-outline-primary" 
                    onclick="showPlaybackModal(
                        '{{ alarm.AlarmId }}', 
                        '{% if alarm.passage %}{{ alarm.passage.MediaDesc }}{% else %}未知位置{% endif %}', 
                        '{{ alarm.ResultDescription or "未知类型" }}', 
                        '{{ alarm.CreateTime.strftime("%Y-%m-%d %H:%M:%S") }}'
                    )">
                <i class="bi bi-play-circle"></i> 播放
            </button>
        </td>  
    </tr>
    {% endfor %}
</tbody>
            </table>
        </div>
    </div>

    <!-- 分页控件 -->
    <div class="mt-4">
        <nav aria-label="分页导航">
            <ul class="pagination justify-content-center">
                <li class="page-item {% if page == 1 %}disabled{% endif %}">
                    <a class="page-link" href="?page={{ page - 1 }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">
                        <i class="bi bi-chevron-left"></i> 上一页
                    </a>
                </li>
                
                {% if total_pages <= 7 %}
                    {% for p in range(1, total_pages + 1) %}
                        <li class="page-item {% if p == page %}active{% endif %}">
                            <a class="page-link" href="?page={{ p }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">{{ p }}</a>
                        </li>
                    {% endfor %}
                {% else %}
                    {% if page <= 4 %}
                        {% for p in range(1, 6) %}
                            <li class="page-item {% if p == page %}active{% endif %}">
                                <a class="page-link" href="?page={{ p }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">{{ p }}</a>
                            </li>
                        {% endfor %}
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                        <li class="page-item"><a class="page-link" href="?page={{ total_pages - 1 }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">{{ total_pages - 1 }}</a></li>
                        <li class="page-item"><a class="page-link" href="?page={{ total_pages }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">{{ total_pages }}</a></li>
                    {% elif page >= total_pages - 3 %}
                        <li class="page-item"><a class="page-link" href="?page=1&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">1</a></li>
                        <li class="page-item"><a class="page-link" href="?page=2&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">2</a></li>
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                        {% for p in range(total_pages - 4, total_pages + 1) %}
                            <li class="page-item {% if p == page %}active{% endif %}">
                                <a class="page-link" href="?page={{ p }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">{{ p }}</a>
                            </li>
                        {% endfor %}
                    {% else %}
                        <li class="page-item"><a class="page-link" href="?page=1&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">1</a></li>
                        <li class="page-item"><a class="page-link" href="?page=2&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">2</a></li>
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                        {% for p in range(page - 2, page + 3) %}
                            <li class="page-item {% if p == page %}active{% endif %}">
                                <a class="page-link" href="?page={{ p }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">{{ p }}</a>
                            </li>
                        {% endfor %}
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                        <li class="page-item"><a class="page-link" href="?page={{ total_pages - 1 }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">{{ total_pages - 1 }}</a></li>
                        <li class="page-item"><a class="page-link" href="?page={{ total_pages }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">{{ total_pages }}</a></li>
                    {% endif %}
                {% endif %}
                
                <li class="page-item {% if page == total_pages %}disabled{% endif %}">
                    <a class="page-link" href="?page={{ page + 1 }}&page_size={{ page_size }}{% if search_query %}&search={{ search_query }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">
                        下一页 <i class="bi bi-chevron-right"></i>
                    </a>
                </li>
            </ul>
        </nav>
        <div class="text-center text-muted mt-2">
            显示 {{ (page - 1) * page_size + 1 }} 到 {{ (page - 1) * page_size + alarms|length }} 条，共 {{ total_alarms }} 条记录
        </div>
    </div>
{% else %}
    <div class="d-flex justify-content-center align-items-center" style="min-height: 400px;">
        <div class="alert alert-primary text-center p-5 rounded-3">
            <div class="mb-3">
                <i class="bi bi-info-circle fs-1 text-primary"></i>
            </div>
            <h4 class="fw-bold">
                {% if search_query or start_date or end_date %}
                    未找到匹配的告警信息
                {% else %}
                    暂无告警数据
                {% endif %}
            </h4>
            <p class="mt-2 text-muted">
                {% if search_query %}
                    没有找到包含 "{{ search_query }}" 的告警信息
                {% elif start_date or end_date %}
                    {% if start_date and end_date %}
                        没有找到 {{ start_date }} 至 {{ end_date }} 的告警信息
                    {% elif start_date %}
                        没有找到 {{ start_date }} 之后的告警信息
                    {% elif end_date %}
                        没有找到 {{ end_date }} 之前的告警信息
                    {% endif %}
                {% else %}
                    系统中没有记录的告警信息，请检查设备连接或稍后再试。
                {% endif %}
            </p>
            {% if search_query or start_date or end_date %}
                <a href="?page=1&page_size={{ page_size }}" class="btn btn-outline-primary mt-3">
                    查看所有告警
                </a>
            {% endif %}
        </div>
    </div>
{% endif %}

<!-- 图片查看模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">告警图片详情</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body d-flex justify-content-center align-items-center p-0" style="min-height: 500px; background-color: #f8f9fa;">
                <!-- 加载状态 -->
                <div id="imageLoading" class="text-center">
                    <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-3 text-muted">图片加载中，请稍候...</p>
                </div>
                <!-- 图片容器 -->
                <div id="imageContainer" class="d-none w-100 h-100">
                    <img id="modalImage" src="" alt="告警图片" class="w-100 h-100 object-fit-contain">
                    <!-- 图片加载失败提示 -->
                    <div id="imageError" class="text-center d-none position-absolute top-50 start-50 translate-middle">
                        <i class="bi bi-exclamation-triangle text-danger fs-1"></i>
                        <p class="mt-3 text-danger fw-medium">图片加载失败，请检查图片路径或尝试刷新页面</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 回放视频模态框 -->
<div class="modal fade" id="playbackModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <div>
                    <h5 class="modal-title">告警回放</h5>
                    <p class="mb-0 small">
                        <span id="playbackLocation">未知位置</span> - 
                        <span id="playbackTime">未知时间</span> - 
                        <span id="playbackType">未知类型</span>
                    </p>
                </div>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0 position-relative">
                <!-- 视频加载指示器 -->
                <div id="videoLoading" style="display: flex; justify-content: center; align-items: center; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 10;">
                    <div class="text-center text-white">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">正在准备视频流...</p>
                    </div>
                </div>
                
                <!-- 视频播放区域 -->
                <div class="ratio ratio-16x9 bg-dark">
                    <!-- 移除画中画功能 -->
                    <video id="playbackVideo" controls disablePictureInPicture class="w-100 h-100"></video>
                </div>
                
                <!-- 播放信息 -->
                <div class="p-3">
                    <div id="playbackInfo" class="alert alert-info py-2 mb-0">
                        正在初始化播放器...
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <!-- 添加截图按钮 -->
                <button id="screenshotBtn" class="btn btn-success me-auto">
                    <i class="bi bi-camera"></i> 截图
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
    // 图片查看功能
    function showImageModal(imagePath) {
        const modal = new bootstrap.Modal(document.getElementById('imageModal'));
        const imgElement = document.getElementById('modalImage');
        const loadingElement = document.getElementById('imageLoading');
        const containerElement = document.getElementById('imageContainer');
        const errorElement = document.getElementById('imageError');
        
        loadingElement.classList.remove('d-none');
        containerElement.classList.add('d-none');
        errorElement.classList.add('d-none');
        
        imgElement.src = `/api/alerts/image/${imagePath}`;
        
        imgElement.onload = function() {
            loadingElement.classList.add('d-none');
            containerElement.classList.remove('d-none');
            errorElement.classList.add('d-none');
        };
        
        imgElement.onerror = function() {
            loadingElement.classList.add('d-none');
            containerElement.classList.remove('d-none');
            errorElement.classList.remove('d-none');
            imgElement.src = '/static/images/default-alert.jpg';
        };
        
        modal.show();
    }
    
    // 截图功能
    function captureScreenshot() {
        const video = document.getElementById('playbackVideo');
        const infoElement = document.getElementById('playbackInfo');
        
        // 检查视频是否准备好
        if (video.readyState < 2) { // 0: HAVE_NOTHING, 1: HAVE_METADATA
            infoElement.innerHTML = '<i class="bi bi-exclamation-triangle"></i> 视频尚未加载，无法截图';
            return;
        }
        
        // 创建canvas元素
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext('2d');
        
        // 将当前视频帧绘制到canvas上
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        try {
            // 转换为数据URL
            const dataURL = canvas.toDataURL('image/png');
            
            // 创建下载链接
            const link = document.createElement('a');
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            link.download = `告警截图_${timestamp}.png`;
            link.href = dataURL;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 显示成功提示
            infoElement.innerHTML = '<i class="bi bi-check-circle"></i> 截图已保存';
            setTimeout(() => {
                if (infoElement.innerHTML.includes('截图已保存')) {
                    infoElement.innerHTML = '<i class="bi bi-play-circle"></i> 准备就绪，正在播放';
                }
            }, 3000);
        } catch (error) {
            console.error('截图失败:', error);
            infoElement.innerHTML = `<i class="bi bi-exclamation-triangle"></i> 截图失败: ${error.message}`;
        }
    }
    
    // 回放视频功能（使用WebSocket和WebRTC）
    function showPlaybackModal(alarmId, location, alertType, alertTime) {
        console.log('开始执行回放，位置:', location, '类型:', alertType, '时间:', alertTime);
        const modal = new bootstrap.Modal('#playbackModal');
        const video = document.getElementById('playbackVideo');
        const infoElement = document.getElementById('playbackInfo');
        const loadingElement = document.getElementById('videoLoading');
        
        // 设置位置、时间和告警类型信息
        document.getElementById('playbackLocation').textContent = location;
        document.getElementById('playbackTime').textContent = alertTime;
        document.getElementById('playbackType').textContent = alertType;
        
        // 重置状态
        video.srcObject = null;
        infoElement.innerHTML = '<i class="bi bi-hourglass"></i> 正在初始化播放器...';
        loadingElement.style.display = 'flex';
        
        // 显示模态框
        modal.show();
        
        let pc = null;
        let ws = null;
        
        // 清理函数
        const cleanup = function() {
            if (ws) {
                ws.close();
                ws = null;
            }
            if (pc) {
                pc.close();
                pc = null;
            }
            video.srcObject = null;
        };
        
        // 监听模态框关闭事件
        $('#playbackModal').on('hidden.bs.modal', cleanup);
        
        // 绑定截图按钮事件
        document.getElementById('screenshotBtn').onclick = function() {
            captureScreenshot();
        };
        
        // 创建WebSocket连接
        console.log('生成：',`ws://${window.location.host}/ws/playback/${alarmId}`);
        ws = new WebSocket(`ws://${window.location.host}/ws/playback/${alarmId}`);
        
        ws.onopen = () => {
            console.log('WebSocket连接已建立');
            infoElement.innerHTML = '<i class="bi bi-hourglass"></i> 正在设置视频流...';
            
            // 创建PeerConnection
            pc = new RTCPeerConnection({
                iceServers: [
                    { urls: "stun:stun.l.google.com:19302" },
                    { urls: "stun:stun1.l.google.com:19302" }
                ]
            });
            
            pc.onicecandidate = (event) => {
                if (event.candidate) {
                    ws.send(JSON.stringify({
                        type: "candidate",
                        candidate: event.candidate
                    }));
                }
            };
            
            pc.oniceconnectionstatechange = () => {
                console.log("ICE连接状态:", pc.iceConnectionState);
                if (pc.iceConnectionState === "connected") {
                    loadingElement.style.display = 'none';
                    infoElement.innerHTML = '<i class="bi bi-play-circle"></i> 准备就绪，正在播放';
                } else if (pc.iceConnectionState === "disconnected" || 
                        pc.iceConnectionState === "failed") {
                    infoElement.innerHTML = '<i class="bi bi-exclamation-triangle"></i> 连接断开';
                }
            };
            
            pc.ontrack = (event) => {
                if (event.track.kind === "video") {
                    video.srcObject = event.streams[0];
                    video.play().catch(e => console.error("播放失败:", e));
                }
            };
            
            // 创建offer
            pc.createOffer({
                offerToReceiveVideo: true,
                offerToReceiveAudio: false
            })
            .then(offer => pc.setLocalDescription(offer))
            .then(() => {
                ws.send(JSON.stringify({
                    type: "offer",
                    offer: pc.localDescription
                }));
            })
            .catch(error => {
                console.error("创建offer失败:", error);
                infoElement.innerHTML = '<i class="bi bi-exclamation-triangle"></i> 创建连接失败';
            });
        };
        
        ws.onmessage = async (event) => {
            const message = JSON.parse(event.data);
            
            if (message.type === "answer" && pc) {
                await pc.setRemoteDescription(new RTCSessionDescription(message.answer));
            } 
            else if (message.type === "candidate" && pc) {
                try {
                    await pc.addIceCandidate(new RTCIceCandidate(message.candidate));
                } catch (e) {
                    console.error("添加ICE候选失败:", e);
                }
            }
            else if (message.type === "error") {
                console.error('服务器错误:', message.message);
                infoElement.innerHTML = `<i class="bi bi-exclamation-triangle"></i> 错误: ${message.message}`;
                loadingElement.style.display = 'none';
            }
        };
        
        ws.onerror = (error) => {
            console.error('WebSocket错误:', error);
            infoElement.innerHTML = '<i class="bi bi-exclamation-triangle"></i> 连接错误';
            loadingElement.style.display = 'none';
        };
        
        ws.onclose = () => {
            console.log('WebSocket连接关闭');
            infoElement.innerHTML = '<i class="bi bi-x-circle"></i> 连接已关闭';
            loadingElement.style.display = 'none';
        };
    }
        
    // 重试函数
    function retryPlayback(alarmId, channel) {
        const infoElement = document.getElementById('playbackInfo');
        infoElement.innerHTML = '<i class="bi bi-arrow-repeat"></i> 正在重试...';
        showPlaybackModal(alarmId, channel, alertType);
    }
    
    // 全选/取消全选功能
    function toggleSelectAll(checkbox) {
        const checkboxes = document.querySelectorAll('.alert-checkbox');
        checkboxes.forEach(cb => {
            cb.checked = checkbox.checked;
        });
        updateDeleteButtonState();
    }
    
    // 更新删除按钮状态
    function updateDeleteButtonState() {
        const selectedCount = document.querySelectorAll('.alert-checkbox:checked').length;
        const deleteBtn = document.getElementById('deleteSelectedBtn');
        deleteBtn.disabled = selectedCount === 0;
        deleteBtn.innerHTML = `<i class="bi bi-trash"></i> 删除选中项 (${selectedCount})`;
    }
    
    // 删除选中的告警
    function deleteSelectedAlerts() {
        const selectedCheckboxes = document.querySelectorAll('.alert-checkbox:checked');
        if (selectedCheckboxes.length === 0) {
            alert('请先选择要删除的告警');
            return;
        }
        
        if (!confirm(`确定要删除选中的 ${selectedCheckboxes.length} 条告警记录吗？`)) {
            return;
        }
        
        const alertIds = Array.from(selectedCheckboxes).map(cb => parseInt(cb.value));
        
        fetch('/api/delete-alerts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ alert_ids: alertIds }) 
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert(data.message);
                location.reload();
            } else {
                alert('删除失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('删除操作出错:', error);
            alert('删除操作出错: ' + error.message);
        });
    }
</script>
{% endblock %}